﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using GeneralLibs;
using BasicForms;
using Lists;
using System.Reflection;
using ListForms;

namespace SAMSON_EPOXCY
{
    public partial class FrmMain : RibbonForm
    {
        DBDataContext db = new DBDataContext(GeneralLibs.LocalSettings.ConnectString);
        public FrmMain()
        {
            InitializeComponent();
            InitSkinGallery();
            this.Load += new EventHandler(FrmMain_Load);
            this.FormClosed += new FormClosedEventHandler(FrmMain_FormClosed);
        }

        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        private void FrmMain_Load(object sender, System.EventArgs e)
        {
            UserLookAndFeel.Default.SetSkinStyle(LocalSettings.HeThong["SkinName"].ToString());
            if (DesignMode) return;
            try
            {
                ribbonControl.ForceInitialize();
                foreach (DevExpress.Skins.SkinContainer skin in DevExpress.Skins.SkinManager.Default.Skins)
                {
                    BarCheckItem item = ribbonControl.Items.CreateCheckItem(skin.SkinName, false);
                    item.Tag = skin.SkinName;
                }

                SetGUI();
                LocalSettings.HeThong.HardwareID = CommonLib.GetMacAddressID();

                if (LocalSettings.HeThong.AutoLogin)
                {
                    BasicForms.FrmProgressBar.StartShowProgress();
                    BasicForms.FrmProgressBar.Status = "Login...";

                    Account.CurAccount = Account.Login(LocalSettings.HeThong.TenTruyCap, LocalSettings.HeThong.Password);

                    BasicForms.FrmProgressBar.FinishShowProgress();

                    if (Account.CurAccount != null)
                    {
                        BasicForms.FrmProgressBar.FinishShowProgress();
                    }
                    else
                    {
                        BasicForms.FrmProgressBar.FinishShowProgress();
                        BasicForms.FrmWarning.Show("Login Failure!");
                    }
                }
                else
                {
                    LoginLogout();
                }

                SetGUI();
            }
            catch (Exception ex)
            {
                BasicForms.FrmWarning.Show(ex.Message);
            }
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                //LocalSettings.HeThong["SkinName"] = defaultLookAndFeel.LookAndFeel.SkinName;
                LocalSettings.HeThong["SkinName"] = UserLookAndFeel.Default.SkinName;
                LocalSettings.HeThong.Save2File();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    case Keys.F1:
                        BasicForms.FrmBase.ShowHelp(this.Name);
                        break;
                    case Keys.Control | Keys.L:
                    case Keys.Control | Keys.D:
                        LoginLogout();
                        break;
                    //Some hide functions
                    case Keys.Control | Keys.Shift | Keys.Alt | Keys.O:
                        FrmDanhSachFunction frm = new FrmDanhSachFunction();
                        frm.RequestFunction += new FrmBase.OnRequestFunction(showedForm_RequestFunction);
                        frm.Show();
                        break;
                }
                return base.ProcessCmdKey(ref msg, keyData);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

        public void LoginLogout()
        {
            try
            {
                if (Account.CurAccount == null)//login
                {
                    while (true)
                    {
                        try
                        {
                            FrmLogin frmLogin = new FrmLogin();
                            if (frmLogin.ShowDialog() == DialogResult.OK)
                            {
                                Account.CurAccount = Account.Login(frmLogin.UserName, frmLogin.Password);
                                if (Account.CurAccount != null) break;
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception loginEx)
                        {
                            BasicForms.FrmWarning.Show("Login Error", loginEx.Message);
                        }
                    }
                }
                else//logout
                {
                    while (Application.OpenForms.Count > 1)
                        Application.OpenForms[1].Close();

                    Account.CurAccount = null;
                }
                SetGUI();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        public void SetGUI()
        {
            if (Account.CurAccount != null)
            {
                btnReceiving.Enabled = true;
                btnDelivering.Enabled = true;
                foreach (RibbonPage ribbonPage in ribbonControl.Pages)
                {
                    foreach (RibbonPageGroup pageGroup in ribbonPage.Groups)
                    {
                        foreach (Object itemLink in pageGroup.ItemLinks)
                        {
                            string tag = null;
                            if (itemLink is BarButtonItemLink) tag = (string)(itemLink as BarButtonItemLink).Item.Tag;
                            else if (itemLink is BarSubItemLink) tag = (string)(itemLink as BarSubItemLink).Item.Tag;
                            Function function = db.Functions.FirstOrDefault(p => p.Name == tag);
                            Role_Function rol_function = null;
                            if (function != null)
                            {
                                rol_function = db.Role_Functions.FirstOrDefault(p => p.FunctionID == function.FunctionID && p.RoleID == Account.CurAccount.AccessAuthorityID);
                            }
                            if (itemLink is BarButtonItemLink)
                            {
                                (itemLink as BarButtonItemLink).Item.Enabled = (function != null && rol_function != null);
                            }
                            else if (itemLink is BarSubItemLink)
                            {
                                (itemLink as BarSubItemLink).Item.Enabled = (function != null && rol_function != null);
                            }
                            else if (itemLink is RibbonGalleryBarItem)
                            {
                                (itemLink as RibbonGalleryBarItem).Enabled = true;
                            }
                        }
                    }
                }
                mainTableLayout.Enabled = true;
                foreach (Control ctr in mainTableLayout.Controls)
                {
                    if (ctr is CustomControls.CustomButton)
                    {
                        string tag = (string)ctr.Tag;
                        Function function = db.Functions.FirstOrDefault(p => p.Name == tag);
                        Role_Function role_function = null;
                        if (function != null)
                        {
                            role_function = db.Role_Functions.FirstOrDefault(p => p.FunctionID == function.FunctionID && p.RoleID == Account.CurAccount.AccessAuthorityID);
                        }
                        (ctr as CustomControls.CustomButton).Enabled = (function != null && role_function != null);
                    }
                }

                btnLogInOut.Caption = "&Logout";
                barStaticItemCurentUser.Caption = string.Format("Curent User: {0}", Account.CurAccount.AccountName);
            }
            else
            {
                btnReceiving.Enabled = false;
                btnDelivering.Enabled = false;
                foreach (RibbonPage ribbonPage in ribbonControl.Pages)
                {
                    foreach (RibbonPageGroup pageGroup in ribbonPage.Groups)
                    {
                        foreach (Object itemLink in pageGroup.ItemLinks)
                        {
                            if (itemLink is BarButtonItemLink) (itemLink as BarButtonItemLink).Item.Enabled = false;
                            else if (itemLink is BarSubItemLink)
                            {
                                (itemLink as BarSubItemLink).Item.Enabled = false;
                            }
                        }
                    }
                }
                btnLogInOut.Enabled = true;
                btnChangePassword.Enabled = false;
                btnLogInOut.Caption = "&Login";
                mainTableLayout.Enabled = false;
            }
            barStaticItemVersion.Caption = string.Format("Version {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
        }

        public void CallFunction(string function)
        {
            //#region Neu khong co quyen gi ca thi quit
            //Right right = User.CurUser.GetRight(function);
            //if (right == CustomSecurity.Right.None) return;
            //#endregion
            Function func = db.Functions.FirstOrDefault(p => p.Name == function);
            if (func != null)
            {
                CustomSecurity.CallFunction callFunction = CustomSecurity.CallFunctionList.GetByKeys(func.FunctionID);
                if (callFunction != null)
                {
                    CallFunction(function, callFunction.DllName, callFunction.FormName);
                }
            }
        }

        public void CallFunction(string function, string dllName, string formName)
        {
            try
            {
                BasicForms.FrmBase showedForm = null;
                switch (function)
                {
                    default:
                        Type type = null;
                        if (string.IsNullOrEmpty(dllName))
                        {
                            type = Type.GetType(formName);
                        }
                        else
                        {
                            type = Assembly.LoadFrom(Application.StartupPath + "\\" + dllName).GetType(formName);
                        }
                        if (type != null)
                        {
                            foreach (Form openedForm in Application.OpenForms)
                            {
                                if (openedForm.GetType() == type)
                                {
                                    openedForm.BringToFront();
                                    return;
                                }
                            }
                            try
                            {
                                showedForm = (BasicForms.FrmBase)Activator.CreateInstance(type);
                            }
                            catch
                            {
                                //Lý do đặt try - catch ở đây: Trong hàm khởi tạo hoặc hàm Load của đối tượng được tạo ra mà bị lỗi, 
                                //thì phương thức Activator.CreateInstance() không tạo được thể hiện nào, vì vậy sẽ văng Exception tại đây
                            }
                        }
                        break;
                }
                if (showedForm != null)
                {
                    showedForm.RequestFunction += new BasicForms.FrmBase.OnRequestFunction(showedForm_RequestFunction);
                    showedForm.Show();
                }

            }
            catch (CustomException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void showedForm_RequestFunction(string function)
        {
            CallFunction(function);
        }

        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }

        private void btnLogInOut_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoginLogout();
        }

        private void Button_Click(object sender, ItemClickEventArgs e)
        {
            try
            {
                CallFunction(e.Item.Tag as string);
            }
            catch { }
        }

        private void ButtonToggle_Click(object sender, EventArgs e)
        {
            if (ModifierKeys == Keys.Control && (sender is Button))
            {
                CallFunction(((sender as Button).Tag as string).Replace("FrmEdit", "Frm"));
            }
            else CallFunction((sender as Button).Tag as string);
        }

        private void btnSupport_ItemClick(object sender, ItemClickEventArgs e)
        {
            Process.Start(Application.StartupPath + @"\Support.doc");
        }
    }
}